package com.example.yian.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.yian.entity.User;
import com.example.yian.mapper.UserMapper;
import com.example.yian.util.JwtUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Service
public class WeChatAuthService {

    @Autowired
    private UserMapper userMapper;

    private final String appId = "wx9b1dda4b16aafec1";
    private final String appSecret = "3e93c93d8818f7959d9e390d4d8e86f4";
    private final ObjectMapper objectMapper = new ObjectMapper();

    public Optional<User> login(String code) {
//        String url = "https://api.weixin.qq.com/sns/jscode2session";
//        RestTemplate restTemplate = new RestTemplate();
//        Map<String, String> params = new HashMap<>();
//        params.put("appid", appId);
//        params.put("secret", appSecret);
//        params.put("js_code", code);
//        params.put("grant_type", "authorization_code");
//
//        Map<String, Object> response = restTemplate.getForObject(url, Map.class, params);
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        String responseStr = restTemplate.getForObject(url, String.class);
        try {
            Map<String, Object> response = objectMapper.readValue(responseStr, new TypeReference<Map<String, Object>>() {
            });
           if (response != null && response.containsKey("openid")) {
                String openid = (String) response.get("openid");
                String sessionKey = (String) response.get("session_key");

                QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("openid", openid);
                User user = userMapper.selectOne(queryWrapper);
                LocalDateTime now = LocalDateTime.now();
                long expirationTime = 99 *365 * 24 * 3600 * 1000L; // 假设 token 有效期为1小时，按需调整

                if (user == null) {
                    user = new User();
                    user.setOpenid(openid);
                    user.setSessionKey(sessionKey);
                    user.setToken(JwtUtils.generateToken(openid));
                    long expirationInMillis =now.plusSeconds(expirationTime).toInstant(ZoneOffset.UTC).toEpochMilli();
                    user.setTokenExpiration(new Timestamp(expirationInMillis)); // 设置 token 过期时间
                    userMapper.insert(user);
                } else {
                    user.setSessionKey(sessionKey);
                    userMapper.updateById(user);
                }

                // String token = JwtUtils.generateToken(openid);
                return Optional.of(user);
            }
        } catch (IOException e) {
            // 处理解析异常
            e.printStackTrace();
            return Optional.empty();
        }

        return Optional.empty();
    }

    public Optional<Long> getUserIdFromToken(String token) {
        try {
            Claims claims = JwtUtils.parseToken(token);
            String openid = claims.getSubject();
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("openid", openid);
            User user = userMapper.selectOne(queryWrapper);
            return Optional.ofNullable(user).map(User::getUserId);
        } catch (Exception e) {
            return Optional.empty();
        }
    }
}
